package dao

import (
	"github.com/rs/zerolog/log"
	"github.com/xormplus/xorm"
	"satellite/model"
)

type Engine struct {
	*xorm.Engine
}

// Transaction 事务自动提交封装
func (e *Engine) Transaction(f func(s *xorm.Session) error) {
	s := e.NewSession()
	defer s.Close()
	err := s.Begin()
	if err != nil {
		return
	}
	err = f(s)
	if err != nil {
		err = s.Rollback()
		if err != nil {
			log.Err(err).Send()
			return
		}
		return
	}
	err = s.Commit()
	if err != nil {
		log.Err(err).Send()
		return
	}
}

func (e *Engine) GetGroupStatus() (*model.Status, error) {
	status := new(model.Status)
	err := e.Table(new(model.GroupMembers)).Join("left", new(model.GroupStats), "member_id").
		Asc("member_host").Find(status)
	if err != nil {
		return nil, err
	}
	return status, nil
}
